package main

func jobAdd(devices, jType string) {
	var _type int

	switch jType {
	case "kill":
		return
	case "follow":
		_type = typeFollow
	case "check_login":
		_type = typeCheckLogin
	case "fenshen":
		_type = typeFenshen
	case "register":
		_type = typeRegister
	case "upload":
		_type = typeUploadVideo
	case "shua":
		_type = typeShua
	}
	var job = Job{}
	job.Devices = devices
	job.Type = _type
	db.Create(&job)
	go job.handler()
}

func retryFailedJob(id int) {
	var job = Job{}
	if db.Where("id = ?", id).First(&job).RecordNotFound() == true {
		return
	}
	var tasks []Task
	query := db.Where("job_id = ?", job.ID).Find(&tasks)
	if query.Error != nil {
		return
	}

	for _, task := range tasks {
		var t Task
		t = task

		db.Model(&t).Update("status", TaskUnStart)
		if device := monitor.getDevice(task.DeviceID); device != nil {
			device.ch <- task
		}
	}
}

func (j Job) handler() {
	if j.Devices == "all" {
		if j.Type == typeUploadVideo {
			j.runAllUpload()
			return
		}
		j.runAll()
	} else {
		return
	}
}

func (j Job) runAllUpload() {
	monitor.getDevicesByFunc(func(allDevices map[string]*Device) {
		for deviceID, dd := range allDevices {
			for _, p := range dd.Packs {
				var v = Video{}
				if err := db.Where("p_id = ?", p.ID).Where("status = ?", 3).Where("is_use = ?", 0).First(&v).Error; err == nil {
					var task = Task{}
					task.JobID = j.ID
					task.DeviceID = deviceID
					task.PName = p.Name
					task.Type = j.Type
					task.Status = TaskUnStart
					task.Trys = 0
					task.Extra = v.Target
					db.Create(&task)

					v.IsUse = 1
					db.Save(&v)

					select {
					case dd.ch <- task:
					}
				}
			}
		}
	})
}

func (j Job) runAll() {
	monitor.getDevicesByFunc(func(allDevices map[string]*Device) {
		for deviceID, dd := range allDevices {
			for _, p := range dd.Packs {
				var task = Task{}
				task.JobID = j.ID
				task.DeviceID = deviceID
				task.PName = p.Name
				task.Type = j.Type
				task.Status = TaskUnStart
				task.Trys = 0
				db.Create(&task)

				select {
				case dd.ch <- task:
				}
			}
		}
	})
}
